<template>
  <div id="addQuestionPage">
    <h2 style="margin-bottom: 32px">
      {{ titlePrefix }}（{{ TYPE_MAP[type] }}）
    </h2>

    <!-- ====== 基础信息 ====== -->
    <a-descriptions
      :column="2"
      :data="[
        { label: '测评活动 ID', value: appId || '未绑定' },
        { label: '题型', value: TYPE_MAP[type] },
      ]"
      style="margin-bottom: 24px"
    />

    <!-- ====== 题目编辑表单 ====== -->
    <a-form
      :model="questionContent"
      :style="{ width: '620px' }"
      label-align="left"
      auto-label-width
      @submit="handleSubmit"
    >
      <!-- —— 顶部工具 —— -->
      <a-form-item label="题目列表">
        <a-space>
          <a-button @click="addQuestion(questionContent.length)"
            >底部添加题目</a-button
          >
          <!-- 若需 AI 生成可自行放这里 -->
        </a-space>
      </a-form-item>

      <!-- —— 遍历题目 —— -->
      <div
        v-for="(q, qi) in questionContent"
        :key="qi"
        style="margin-bottom: 24px"
      >
        <a-space size="large">
          <h3 style="margin: 8px 0">题目 {{ qi + 1 }}</h3>
          <a-button size="mini" @click="addQuestion(qi + 1)">插入题目</a-button>
          <a-button size="mini" status="danger" @click="deleteQuestion(qi)"
            >删除题目</a-button
          >
        </a-space>

        <!-- 题干 -->
        <a-form-item :label="`题干 ${qi + 1}`">
          <a-input v-model="q.title" placeholder="请输入题干" />
        </a-form-item>

        <!-- ========= 选项型 ========= -->
        <template v-if="isOptionType">
          <a-space size="large">
            <h4>选项列表</h4>
            <a-button size="mini" @click="addOption(q, q.options?.length || 0)"
              >底部添加选项</a-button
            >
          </a-space>

          <a-form-item
            v-for="(opt, oi) in q.options"
            :key="oi"
            :label="`选项 ${oi + 1}`"
            :content-flex="false"
            :merge-props="false"
          >
            <a-form-item label="key"><a-input v-model="opt.key" /></a-form-item>
            <a-form-item label="value"
              ><a-input v-model="opt.value"
            /></a-form-item>
            <a-form-item label="result"
              ><a-input v-model="opt.result"
            /></a-form-item>
            <a-form-item label="score"
              ><a-input-number v-model="opt.score"
            /></a-form-item>

            <a-space>
              <a-button size="mini" @click="addOption(q, oi + 1)"
                >插入</a-button
              >
              <a-button size="mini" status="danger" @click="delOption(q, oi)"
                >删除</a-button
              >
            </a-space>
          </a-form-item>
        </template>

        <!-- ========= 填空 / 简答 ========= -->
        <template v-else>
          <a-space size="large">
            <h4>答案列表</h4>
            <a-button size="mini" @click="addAnswer(q, q.answers?.length || 0)"
              >底部添加答案</a-button
            >
          </a-space>

          <a-form-item
            v-for="(ans, ai) in q.answers"
            :key="ai"
            :label="`答案 ${ai + 1}`"
            :content-flex="false"
            :merge-props="false"
          >
            <a-form-item label="key"><a-input v-model="ans.key" /></a-form-item>
            <a-form-item label="value"
              ><a-input v-model="ans.value"
            /></a-form-item>
            <a-form-item label="score"
              ><a-input-number v-model="ans.score"
            /></a-form-item>

            <a-space>
              <a-button size="mini" @click="addAnswer(q, ai + 1)"
                >插入</a-button
              >
              <a-button size="mini" status="danger" @click="delAnswer(q, ai)"
                >删除</a-button
              >
            </a-space>
          </a-form-item>
        </template>
      </div>

      <!-- —— 提交 —— -->
      <a-form-item>
        <a-button type="primary" html-type="submit" style="width: 120px"
          >提交</a-button
        >
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup lang="ts">
import { ref, watchEffect } from "vue";
import { useRoute, useRouter } from "vue-router";
import message from "@arco-design/web-vue/es/message";
import {
  addQuestionUsingPost,
  editQuestionUsingPost,
  listQuestionVoByPageUsingPost,
} from "@/api/questionController";
import API from "@/api";

/* ---------- 路由参数 ---------- */
const route = useRoute();
const router = useRouter();

const appId = (route.params.appId as string) || ""; // 可为空
const type = route.params.type as string; // 必填

const TYPE_MAP: Record<string, string> = {
  single: "单选题",
  multi: "多选题",
  fill: "填空题",
  subjective: "简答题",
};
const isOptionType = type === "single" || type === "multi";
const titlePrefix = appId ? "创建题目" : "离线创建题目";

/* ---------- 题目内容 ---------- */
const questionContent = ref<API.QuestionContentDTO[]>([]);

/* ---------- 工具函数 ---------- */
const newOption = () => ({ key: "", value: "", result: "", score: 0 });
const newAnswer = () => ({ key: "", value: "", score: 1 });

const addQuestion = (idx: number) => {
  questionContent.value.splice(idx, 0, {
    title: "",
    options: isOptionType ? [] : undefined,
    answers: !isOptionType ? [] : undefined,
  });
};
const deleteQuestion = (idx: number) => questionContent.value.splice(idx, 1);

const addOption = (q: any, idx: number) => {
  q.options ??= [];
  q.options.splice(idx, 0, newOption());
};
const delOption = (q: any, idx: number) => q.options.splice(idx, 1);

const addAnswer = (q: any, idx: number) => {
  q.answers ??= [];
  q.answers.splice(idx, 0, newAnswer());
};
const delAnswer = (q: any, idx: number) => q.answers.splice(idx, 1);

/* ---------- 旧数据加载（仅当有 appId） ---------- */
const oldQuestion = ref<API.QuestionVO>();
const loadData = async () => {
  if (!appId) return;
  const res = await listQuestionVoByPageUsingPost({
    appId,
    current: 1,
    pageSize: 1,
    sortField: "createTime",
    sortOrder: "descend",
  });
  if (res.data.code === 0) {
    oldQuestion.value = res.data.data?.records?.[0];
    if (oldQuestion.value)
      questionContent.value = oldQuestion.value.questionContent || [];
  } else message.error("加载旧题目失败：" + res.data.message);
};
watchEffect(loadData);

/* ---------- 提交 ---------- */
const handleSubmit = async () => {
  if (!type) return;
  const payload: API.QuestionAddRequest = {
    type,
    appId: appId || undefined,
    questionContent: questionContent.value,
  };

  let res;
  if (appId && oldQuestion.value?.id) {
    res = await editQuestionUsingPost({ id: oldQuestion.value.id, ...payload });
  } else {
    res = await addQuestionUsingPost(payload);
  }

  if (res.data.code === 0) {
    message.success("操作成功");
    if (appId) router.push(`/app/detail/${appId}`);
    else router.back();
  } else message.error("失败：" + res.data.message);
};
</script>

<style scoped>
#addQuestionPage :deep(.arco-form-item-label-col) {
  width: 100px;
}
</style>
